package org.apache.ocean;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.lucene.search.Query;
import org.jdom.Element;

/**
 * 
 * @author jasonr
 */
public class FacetRequest implements CElement {
	public List<QueryFacet> queryFacets = new ArrayList<QueryFacet>();
	public List<FieldFacet> fieldFacets = new ArrayList<FieldFacet>();

	public FacetRequest() {
	}
  
	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}
	
	public FacetRequest(Element root) throws Exception {
		for (Element queryFacetElement : XMLUtil.getChildren("queryfacet", root)) {
			queryFacets.add(new QueryFacet(queryFacetElement));
		}
		for (Element fieldFacetElement : XMLUtil.getChildren("fieldfacet", root)) {
			fieldFacets.add(new FieldFacet(fieldFacetElement));
		}
	}

	public static class FieldFacet implements CElement {
		public String field;
    
		public FieldFacet() {}
		
		public String toString() {
			return ReflectionToStringBuilder.toString(this);
		}
		
		public FieldFacet(String field) {
			this.field = field;
		}

		public FieldFacet(Element root) throws Exception {
			XMLUtil.reflectToObject(this, root);
		}

		public Element toElement() throws Exception {
			return XMLUtil.reflectToElement("fieldfacet", this);
		}
	}

	public static class QueryFacet implements CElement {
		public String queryString;
		public String id;
    
		public QueryFacet() {}
		
		public QueryFacet(String id, String queryString) {
			this.id = id;
			this.queryString = queryString;
		}
    
		public String toString() {
			return ReflectionToStringBuilder.toString(this);
		}
		
		public QueryFacet(Element root) throws Exception {
			XMLUtil.reflectToObject(this, root);
		}

		public Element toElement() throws Exception {
			return XMLUtil.reflectToElement("queryfacet", this);
		}
	}

	public Element toElement() throws Exception {
		Element root = new Element("facetrequest");
		if (queryFacets != null) {
			for (QueryFacet queryFacet : queryFacets) {
				root.addContent(queryFacet.toElement());
			}
		}
		if (fieldFacets != null) {
			for (FieldFacet fieldFacet : fieldFacets) {
				root.addContent(fieldFacet.toElement());
			}
		}
		return root;
	}
}
